﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrmField.Plugins
{
    public class ClientChannelManager
    {
        public static Dictionary<Guid, string> RetrieveLatestUsersChannel(List<Guid> users, IOrganizationService service)
        {
            QueryExpression query = new QueryExpression("fsapp_clientchannel");
            query.ColumnSet = new ColumnSet(new string[] { "fsapp_uri", "ownerid", "createdon" });
            query.Criteria.AddCondition(new ConditionExpression("ownerid", ConditionOperator.In, users.ToArray()));
            query.AddOrder("createdon", OrderType.Descending);
            query.AddOrder("ownerid", OrderType.Ascending);

            Dictionary<Guid, string> userChannels = new Dictionary<Guid, string>(users.Count);

            EntityCollection channels = service.RetrieveMultiple(query);
            EntityReference owner = null;
            foreach (Entity channel in channels.Entities)
            {
                owner = channel["ownerid"] as EntityReference;
                if (!userChannels.ContainsKey(owner.Id) &&  channel.Contains("fsapp_uri"))
                    userChannels.Add(owner.Id, channel["fsapp_uri"].ToString());
            }

            return userChannels;
        }
    }
}
